package stdlib.javax.websocket

import java.net.URI
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.websocket.*

@ClientEndpoint
class MyWebSocketClient {
    lateinit var session: Session
    private val messageLatch = CountDownLatch(1)

    @OnOpen
    fun onOpen(session: Session) {
        this.session = session
        println("Connected to server!")
    }

    @OnMessage
    fun onMessage(message: String) {
        println("Received message: $message")
        messageLatch.countDown()
    }

    @OnError
    fun onError(error: Throwable) {
        println("Error occurred: ${error.message}")
    }

    @OnClose
    fun onClose(reason: CloseReason) {
        println("Connection closed with reason: ${reason.reasonPhrase}")
    }

    fun sendMessage(message: String) {
        session.basicRemote.sendText(message)
    }

    fun await() {
        messageLatch.await(5, TimeUnit.SECONDS)
    }
}

fun main() {
    val uri = URI("ws://10.0.0.8:7011/ws")
    val endpoint = MyWebSocketClient()
    val container = ContainerProvider.getWebSocketContainer()
    container.connectToServer(endpoint, uri)

    while (true) {
        println(endpoint.session.isOpen)
        if (!endpoint.session.isOpen) {
            break
        }
        val message = readlnOrNull() ?: break
        println(message)
        endpoint.sendMessage(message)
        endpoint.await()
    }
}